package org.oschina.helper;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.oschina.util.ReflectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

public class JsonHelper {

	private final static Logger logger=LoggerFactory.getLogger(JsonHelper.class);
	
	/**
	 * 转换为JSON
	 * @param obj
	 * @return
	 */
	public static String toJson(Object obj)
	{
		if(obj==null)
			return null;
		
		if(ReflectUtil.isBasic(obj.getClass()))
			return obj.toString();
		
		return JSON.toJSON(obj).toString();
	}
	
	/**
	 * 转换为对象
	 * @param <T>
	 * @param json
	 * @param type
	 * @return
	 */
	public static <T>Object parse(String json,Class<T> type)
	{
		if(StringUtils.isBlank(json))
			return null;
		
		if(ReflectUtil.isBasic(type))
			return ConvertUtils.convert(json, type);
		
		try
		{
			return JSON.parseObject(json,type);
		}
		catch(Exception e)
		{
			logger.info("json转换失败 - ",e);
			return null;
		}
	}
}